package com.smartrobot.smartrobot.util;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Environment;
import android.util.Log;
import com.smartrobot.smartrobot.logToSdCard.LogToSd;
import com.smartrobot.smartrobot.pojo.circleDetailPojo;
import com.smartrobot.smartrobot.pojo.saveFriendListPojo;

/**
 * 文件管理类，用作创建文件夹
 */
public class FileUtil {

	// 项目文件保存位置
	static public final String PHONE_DIR_INNER = Environment
			.getExternalStorageDirectory().toString() + "/SmartRobot/";

	static public final String PICTURE = "Picture/";
	//建立Active记录文件 每一次文件都用不同名字
	static public final String CacheDATA = "Data/";
    static public final String CacheActive = "activeCache/";
    static public final String CacheDetail = "detatilCache/";
    static public final String CacheNews = "newsCache/";
    static public final String CacheStoreActive = "storeActiveCache/";
	
	//创建用户头像UHead
	static public final String headName = "UHead.png";
	static public final String businessPic = "business.png";
	static public final String identifyCard = "identifyCard.png";
    static public final String tempAddPic = "temp.png";
    static public final String TAG = "FileUtil";
	
	//路径名
	static public String activeCircleCachePath = FileUtil.PHONE_DIR_INNER+FileUtil.CacheDATA + FileUtil.CacheActive;
    static public String activeWorldCachePath = FileUtil.PHONE_DIR_INNER+FileUtil.CacheDATA + FileUtil.CacheActive;
    static public String detailCachePath = FileUtil.PHONE_DIR_INNER+FileUtil.CacheDATA + FileUtil.CacheDetail;
    static public String newsCachePath = FileUtil.PHONE_DIR_INNER+FileUtil.CacheDATA + FileUtil.CacheNews;
    static public String storeActiveCachePathName = FileUtil.PHONE_DIR_INNER+FileUtil.CacheDATA + FileUtil.CacheStoreActive;

    //文件名
    static public String activeCircleFileEndName = "ActiveCircleCache.bin";
    static public String activeWorldFileEndName = "ActiveWorldCache.bin";
    static public String detailEndName = ".bin";
    static public String fashionEndName = "fashion.bin";
    static public String educationEndName = "education.bin";
    static public String storeActiveEndName = "storeActive.bin";

    static public String clientPath = FileUtil.PHONE_DIR_INNER + FileUtil.CacheDATA + "client.bin";
	
	static public boolean update = false;

	public static boolean createFile(String path) {
		File file = new File(path);
		try {
            if (!file.exists()) {
                // 文件不存在
                if (file.getParentFile().exists()) {// 父目录存在
                    // 直接创建文件
                    if (!file.createNewFile()) // 创建文件失败
                        return false;
                } else {// 父目录不存在 需要先创建父目录 再创建子目录

                    if (!file.getParentFile().mkdirs()) // 创建父目录失败
                        return false;

                    if (!file.createNewFile()) // 创建文件失败
                        return false;

                }
            }

		} catch (IOException e) {
			return false;
		}
		return true;
	}

    /**
     * 有bug 因为 bitmap类没有实现 序列化 无法写成byte
     *
     * 将图片保存在sd卡中
     *
     * @param path
     * @param pic
     * @return
     */
	static public boolean writeBitmapToSDCard(String path, Bitmap pic) {

		try {
			File file = new File(path);
			FileOutputStream write = new FileOutputStream(file);

			if (!pic.compress(Bitmap.CompressFormat.JPEG, 100, write))
				return false;

			write.flush();
			write.close();

			return true;
		} catch (Exception e) {
			e.printStackTrace();

			return false;
		}

	}

    /**
     * 保存Active到文件中
     */
    static public void writeJsonToFile(List<Active> activeList,String fileName) throws FileNotFoundException, IOException{

        ObjectOutputStream objWrite ;

        objWrite = new ObjectOutputStream(new FileOutputStream(new File(fileName),false));

        //将一条条active存进文件中
        for(int i=0;i<activeList.size();i++)
            objWrite.writeObject(activeList.get(i));//将list写进文件中
        objWrite.flush();
        objWrite.reset();//否则下次写进的内容无法识别
        objWrite.close();//关闭io流

    }




    /**
     * 从文件中获取Active数据
     */
    static public List<Active> readJsonToFile(String fileName,int start,int end) throws Exception{

        List<Active> activeList = new ArrayList<Active>();

        ObjectInputStream objReader = new ObjectInputStream(new FileInputStream(new File(fileName)));
        //将一条条active从文件中拿出来，根据需要获得相应的数据
        try{
            for(int i=0;i<end;i++){
                Active active = (Active)objReader.readObject();
                if(i>=start){
                    //拿出文件里面某几条数据
                    activeList.add(active);
                    System.out.println("写进去了"+" "+ i +" "+start);
                }
            }
        }catch(Exception e){

            Log.d(TAG, "读完文件数据");
//            e.printStackTrace();

        }

        objReader.close();//关闭io流

        return activeList;
    }


    /**
     * 保存News到文件中
     */
    static public void writeNewsToFile(List<News> newsList,String fileName){

        ObjectOutputStream objWrite = null;

        try{

        objWrite = new ObjectOutputStream(new FileOutputStream(new File(fileName),false));
        //将一条条active存进文件中
        for(int i=0;i<newsList.size();i++)
            objWrite.writeObject(newsList.get(i));//将list写进文件中
        objWrite.flush();
        objWrite.reset();//否则下次写进的内容无法识别
        objWrite.close();//关闭io流
        }catch (Exception e){

            LogToSd.error("写新闻错误:"+e.toString());

        }

    }


    /**
     * 从文件中获取News数据
     */
    static public List<News> readNewsFromFile(String fileName){

        List<News> activeList = new ArrayList<News>();
        ObjectInputStream objReader = null;

        try{
        objReader = new ObjectInputStream(new FileInputStream(new File(fileName)));
        //将一条条active从文件中拿出来，根据需要获得相应的数据
        try{
            while (true){
                News news = (News)objReader.readObject();
                    //拿出文件里面某几条数据
                    activeList.add(news);
            }

        }catch(Exception e){

            Log.d(TAG, "读完文件数据");
//            e.printStackTrace();
            LogToSd.error("读新闻错误:"+e.toString());
        }
            objReader.close();//关闭io流

        }catch (Exception e){

            LogToSd.error("读新闻错误:"+e.toString());

        }

        return activeList;
    }

    /**
     * 保存News到文件中
     */
    static public void writeStoreActiveToFile(List<StoreActive> storeActiveList,String fileName){

        ObjectOutputStream objWrite = null;

        try{

            objWrite = new ObjectOutputStream(new FileOutputStream(new File(fileName),false));
            //将一条条active存进文件中
            for(int i=0;i<storeActiveList.size();i++)
                objWrite.writeObject(storeActiveList.get(i));//将list写进文件中
            objWrite.flush();
            objWrite.reset();//否则下次写进的内容无法识别
            objWrite.close();//关闭io流
        }catch (Exception e){

            LogToSd.error("写新闻错误:"+e.toString());

        }

    }


    /**
     * 从文件中获取News数据
     */
    static public List<StoreActive> readStoreActiveFromFile(String fileName){

        List<StoreActive> activeList = new ArrayList<StoreActive>();
        ObjectInputStream objReader = null;

        try{
            objReader = new ObjectInputStream(new FileInputStream(new File(fileName)));
            //将一条条active从文件中拿出来，根据需要获得相应的数据
            try{
                while (true){
                    StoreActive storeActive = (StoreActive)objReader.readObject();
                    //拿出文件里面某几条数据
                    activeList.add(storeActive);
                }

            }catch(Exception e){

                Log.d(TAG, "读完文件数据");
//            e.printStackTrace();
                LogToSd.error("读新闻错误:"+e.toString());
            }
            objReader.close();//关闭io流

        }catch (Exception e){

            LogToSd.error("读新闻错误:"+e.toString());

        }

        return activeList;
    }


    /**
     * 保存schedule到文件中
     */
    static public void writeScheduleToFile(List<Schedule> activeList,String fileName) throws FileNotFoundException, IOException{

        ObjectOutputStream objWrite ;

        objWrite = new ObjectOutputStream(new FileOutputStream(new File(fileName),false));

        //将一条条active存进文件中
        for(int i=0;i<activeList.size();i++)
            objWrite.writeObject(activeList.get(i));//将list写进文件中

        objWrite.flush();
        objWrite.reset();//否则下次写进的内容无法识别
        objWrite.close();//关闭io流

    }


    /**
     * 从文件中获取schedule数据
     */
    static public List<Schedule> readScheduleToFile(String fileName) {

        List<Schedule> scheduleList = new ArrayList<Schedule>();
        ObjectInputStream objReader = null;
        try{
        objReader = new ObjectInputStream(new FileInputStream(new File(fileName)));
        //将一条条Schedule从文件中拿出来，根据需要获得相应的数据

            while(true) {
                Schedule schedule = (Schedule) objReader.readObject();
                //拿出文件里面某几条数据
                scheduleList.add(schedule);
            }

        }catch(Exception e){

            try {
                objReader.close();//关闭io流
            }catch (Exception e1){
                Log.d(TAG, "读完文件数据");
                LogToSd.debug("读文件错误"+e.toString());
            }
//            e.printStackTrace();
            Log.d(TAG, "读完文件数据");
            LogToSd.debug("读文件错误"+e.toString());
//            e.printStackTrace();

        }

        return scheduleList;
    }




    /*
    * 保存好友列表到文件中(或者朋友圈详情)
     */
    public static void saveCircleMsgToFile(Object pojo,String fileName,Context context) {
        try{

            if(fileName==null||fileName.equals("")){
                return;
            }

            FileOutputStream outputStream = context.openFileOutput(fileName,
                    0);
            ObjectOutputStream objWrite ;
            objWrite = new ObjectOutputStream(outputStream);
            objWrite.writeObject(pojo);//写进文件中
            objWrite.flush();
            objWrite.reset();//否则下次写进的内容无法识别
            objWrite.close();//关闭io流

        }catch (Exception e){
            LogToSd.error("朋友圈信息写入文件失败");
            LogToSd.error(e.getMessage());
            LogToSd.error(fileName);
            LogToSd.error(pojo.toString());
            Log.e("==========朋友圈信息=========","写入文件失败");
        }

    }



    /*
    * 从文件中读取出朋友圈信息
     */
    public static Object ReadCircleMsgFromFile(String fileName,Context context){
        try {
            FileInputStream outputStream = context.openFileInput(fileName);
            ObjectInputStream objReader = new ObjectInputStream(outputStream);
            return objReader.readObject();
        } catch (Exception e) {
            LogToSd.error("ReadCircleMsgFromFile 文件读取失败");
            LogToSd.error(e.getMessage());
            LogToSd.error(fileName);
            Log.e("==========读取文件失败=========", e.toString());
            return null;
        }

    }

    //使用递归方法删除文件
    public static void deleteFile(File file){

        if(file.exists()){
            if(file.isFile()) file.delete();
            else if(file.isDirectory()){//若是文件夹
                File []f = file.listFiles();//获得文件夹里的内容，使用递归逐个删除
                for(int i=0;i<f.length;i++){
                    deleteFile(f[i]);//递归删除
                }
            }
        }else
        {
            System.out.println("文件不存在");
        }

    }

    //使用递归方法删除日程文件
    public static void deleteDetailFile(File file,String noDelete[]){

        if(file.exists()){
             if(file.isDirectory()){//若是文件夹
                File []f = file.listFiles();//获得文件夹里的内容，使用递归逐个删除
                for(int i=0; f.length > 3 && i<f.length;i++){
                    if(!f[i].getAbsolutePath().equals(noDelete[0]))
                           if(!f[i].getAbsolutePath().equals(noDelete[1]))
                                if(!f[i].getAbsolutePath().equals(noDelete[2]))
                                {
                                    Log.d("====删除=======>",f[i].getName());
                                    f[i].delete();

                                }

                }
            }
        }else
        {
            System.out.println("文件不存在");
        }

    }




}
